<template>
  <div class="home-container">
    <!-- 太空背景 -->
    <div class="space-background"></div>
    
    <!-- 星云 -->
    <div class="nebulas-container">
      <div 
        v-for="(nebula, index) in nebulas" 
        :key="index"
        class="nebula"
        :style="{
          left: nebula.x + 'px',
          top: nebula.y + 'px',
          width: nebula.size + 'px',
          height: nebula.size + 'px',
          backgroundColor: nebula.color,
          opacity: nebula.opacity
        }"
      ></div>
    </div>
    
    <!-- 星星 -->
    <div class="stars-container">
      <div 
        v-for="(star, index) in stars" 
        :key="index"
        class="star"
        :style="{
          left: star.x + 'px',
          top: star.y + 'px',
          width: star.size + 'px',
          height: star.size + 'px',
          opacity: star.opacity
        }"
      ></div>
    </div>
    
    <!-- 行星 -->
    <div class="planets-container">
      <div 
        v-for="(planet, index) in planets" 
        :key="index"
        class="planet-wrapper"
        :style="{
          left: planet.x + 'px',
          top: planet.y + 'px'
        }"
      >
        <!-- 行星光环 -->
        <div 
          v-if="planet.hasRing"
          class="planet-ring"
          :style="{
            width: (planet.size * 2.5) + 'px',
            height: (planet.size * 2.5) + 'px',
            borderColor: planet.color
          }"
        ></div>
        <!-- 行星本体 -->
        <div 
          class="planet"
          :style="{
            width: planet.size + 'px',
            height: planet.size + 'px',
            backgroundColor: planet.color
          }"
        ></div>
      </div>
    </div>
    
    <!-- 彗星 -->
    <div class="comets-container">
      <div 
        v-for="(comet, index) in comets" 
        :key="index"
        class="comet"
        :style="{
          left: comet.x + 'px',
          top: comet.y + 'px',
          width: comet.size + 'px',
          height: comet.size + 'px',
          opacity: comet.opacity
        }"
      ></div>
    </div>
    
    <!-- 主内容 -->
    <div class="content">
      <div class="welcome-content">
        <h1 class="title">宇宙探索之旅</h1>
        <p class="subtitle">欢迎来到浩瀚无垠的宇宙</p>
        
        <div class="navigation">
          <button @click="goToGallery" class="nav-btn">探索星际画廊</button>
          <!-- 更新链接，直接跳转到主页面 -->
          <button @click="goToMusic" class="nav-btn" style="margin-top: 15px;">欣赏宇宙音乐</button>
          <button @click="goToVideo" class="nav-btn" style="margin-top: 15px;">观看太空视频</button>
        </div>
        
        <div class="music-status">
          <p>太空音乐播放中...</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
// @ts-ignore
import { Howl } from 'howler'
import { useRouter } from 'vue-router'

const router = useRouter()

// 音频相关
const isPlaying = ref(true) // 默认为播放状态
const currentTime = ref(0)
const duration = ref(0)
let sound: Howl | null = null
let updateInterval: number | null = null

// 太空元素相关
const stars = ref<Array<{x: number, y: number, size: number, opacity: number, twinkleSpeed: number}>>([])
const planets = ref<Array<{x: number, y: number, size: number, color: string, speed: number, hasRing: boolean}>>([])
const comets = ref<Array<{x: number, y: number, size: number, opacity: number, speedX: number, speedY: number}>>([])
const nebulas = ref<Array<{x: number, y: number, size: number, color: string, opacity: number}>>([])

// 添加跳转到各个页面的函数
const goToGallery = () => {
  router.push('/gallery')
}

const goToMusic = () => {
  router.push('/music')
}

const goToVideo = () => {
  router.push('/video')
}

// 初始化太空元素
const initSpaceElements = () => {
  // 创建星星（更多星星，包括不同亮度）
  stars.value = []
  for (let i = 0; i < 300; i++) {
    stars.value.push({
      x: Math.random() * window.innerWidth,
      y: Math.random() * window.innerHeight,
      size: Math.random() * 3 + 1,
      opacity: Math.random() * 0.9 + 0.1,
      twinkleSpeed: Math.random() * 0.03 + 0.005
    })
  }
  
  // 创建行星（包括带光环的行星）
  planets.value = []
  const planetColors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#9370DB']
  for (let i = 0; i < 7; i++) {
    planets.value.push({
      x: Math.random() * window.innerWidth,
      y: Math.random() * window.innerHeight,
      size: Math.random() * 40 + 20,
      color: planetColors[Math.floor(Math.random() * planetColors.length)],
      speed: Math.random() * 0.3 + 0.05,
      hasRing: Math.random() > 0.7 // 30%的行星有光环
    })
  }
  
  // 创建彗星
  comets.value = []
  for (let i = 0; i < 5; i++) {
    comets.value.push({
      x: Math.random() * window.innerWidth,
      y: Math.random() * window.innerHeight,
      size: Math.random() * 4 + 2,
      opacity: Math.random() * 0.8 + 0.2,
      speedX: (Math.random() - 0.5) * 3,
      speedY: (Math.random() - 0.5) * 3
    })
  }
  
  // 创建星云
  nebulas.value = []
  const nebulaColors = ['rgba(100, 108, 255, 0.2)', 'rgba(255, 107, 107, 0.2)', 'rgba(78, 205, 196, 0.2)']
  for (let i = 0; i < 5; i++) {
    nebulas.value.push({
      x: Math.random() * window.innerWidth,
      y: Math.random() * window.innerHeight,
      size: Math.random() * 200 + 100,
      color: nebulaColors[Math.floor(Math.random() * nebulaColors.length)],
      opacity: Math.random() * 0.1 + 0.05
    })
  }
}

// 更新太空动画
const updateSpaceAnimation = () => {
  // 更新星星闪烁效果
  stars.value.forEach(star => {
    star.opacity = 0.1 + Math.abs(Math.sin(Date.now() * star.twinkleSpeed)) * 0.9
  })
  
  // 更新行星位置
  planets.value.forEach(planet => {
    planet.x += planet.speed
    if (planet.x > window.innerWidth + planet.size) {
      planet.x = -planet.size
      planet.y = Math.random() * window.innerHeight
    }
  })
  
  // 更新彗星位置
  comets.value.forEach(comet => {
    comet.x += comet.speedX
    comet.y += comet.speedY
    
    // 边界检测，彗星移出屏幕后重新生成
    if (comet.x < -comet.size || comet.x > window.innerWidth + comet.size || 
        comet.y < -comet.size || comet.y > window.innerHeight + comet.size) {
      // 重新生成彗星
      comet.x = Math.random() > 0.5 ? -comet.size : window.innerWidth + comet.size
      comet.y = Math.random() * window.innerHeight
      comet.speedX = (Math.random() - 0.5) * 3
      comet.speedY = (Math.random() - 0.5) * 3
    }
  })
}

// 动画循环
let animationFrameId: number
const animate = () => {
  updateSpaceAnimation()
  animationFrameId = requestAnimationFrame(animate)
}

// 音频控制函数
const initBackgroundMusic = () => {
  if (!sound) {
    // 初始化音频对象，使用新的MP3文件路径
    sound = new Howl({
      src: ['/static/mp3/yi-sheng-suo-ai.mp3'],
      html5: true,
      autoplay: true, // 自动播放
      loop: true, // 循环播放
      volume: 0.7, // 设置音量
      onplay: () => {
        isPlaying.value = true
        duration.value = sound ? sound.duration() : 0
        startProgressUpdate()
      },
      onpause: () => {
        isPlaying.value = false
        stopProgressUpdate()
      },
      onstop: () => {
        isPlaying.value = false
        stopProgressUpdate()
      },
      onend: () => {
        isPlaying.value = false
        stopProgressUpdate()
        currentTime.value = 0
      }
    })
  }
}

const startProgressUpdate = () => {
  stopProgressUpdate() // 先清除之前的定时器
  updateInterval = window.setInterval(() => {
    if (sound) {
      currentTime.value = sound.seek()
      duration.value = sound.duration()
    }
  }, 1000)
}

const stopProgressUpdate = () => {
  if (updateInterval) {
    clearInterval(updateInterval)
    updateInterval = null
  }
}

// const formatTime = (seconds: number) => {
//   const mins = Math.floor(seconds / 60)
//   const secs = Math.floor(seconds % 60)
//   return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
// }

// 生命周期钩子
onMounted(() => {
  initSpaceElements()
  animate()
  
  // 初始化背景音乐
  initBackgroundMusic()
  
  // 添加窗口大小调整监听器
  window.addEventListener('resize', initSpaceElements)
})

onBeforeUnmount(() => {
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
  }
  
  stopProgressUpdate()
  
  if (sound) {
    sound.unload()
  }
  
  window.removeEventListener('resize', initSpaceElements)
})
</script>

<style scoped>
.home-container {
  position: relative;
  width: 100%;
  min-height: calc(100vh - 60px - 300px); /* 减去头部和底部的高度，适配MainContent布局 */
  overflow: hidden;
  background: linear-gradient(135deg, #0f0c29, #302b63, #24243e); /* 深空渐变背景 */
  color: #ffffff; /* 白色文字 */
  font-family: 'Arial', sans-serif;
  padding-top: 0;
  box-sizing: border-box;
  margin: 0; /* 移除可能的外边距 */
}

.space-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(ellipse at bottom, #1b2735 0%, #090a0f 100%);
  z-index: 0;
}

.nebulas-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.nebula {
  position: absolute;
  border-radius: 50%;
  filter: blur(30px);
  pointer-events: none;
}

.stars-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 2;
}

.star {
  position: absolute;
  background: #ffffff;
  border-radius: 50%;
  pointer-events: none;
  box-shadow: 0 0 5px #ffffff;
}

.planets-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 2;
}

.planet-wrapper {
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
}

.planet-ring {
  position: absolute;
  border-radius: 50%;
  border: 2px solid;
  opacity: 0.3;
}

.planet {
  position: relative;
  border-radius: 50%;
  box-shadow: 0 0 20px rgba(255, 255, 255, 0.2);
  z-index: 3;
}

.comets-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 2;
}

.comet {
  position: absolute;
  background: linear-gradient(90deg, transparent, #ffffff, transparent);
  border-radius: 50%;
  pointer-events: none;
  box-shadow: 0 0 15px #ffffff;
  transform: rotate(45deg);
}

.content {
  position: relative;
  z-index: 3;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  text-align: center;
}

.welcome-content {
  background: rgba(15, 12, 41, 0.7); /* 半透明深空背景 */
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5); /* 深色阴影 */
  max-width: 500px;
  width: 90%;
  animation: fadeIn 1s ease-in;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.title {
  font-size: 2.5rem;
  margin-bottom: 10px;
  text-shadow: 0 0 20px rgba(100, 108, 255, 0.8); /* 发光效果 */
  animation: pulse 3s infinite;
  color: #ffffff; /* 白色标题 */
  font-weight: bold;
}

@keyframes pulse {
  0% { transform: scale(1); text-shadow: 0 0 20px rgba(100, 108, 255, 0.8); }
  50% { transform: scale(1.05); text-shadow: 0 0 30px rgba(100, 108, 255, 1); }
  100% { transform: scale(1); text-shadow: 0 0 20px rgba(100, 108, 255, 0.8); }
}

.subtitle {
  font-size: 1.2rem;
  margin-bottom: 30px;
  opacity: 0.9;
  color: #cccccc; /* 浅灰色副标题 */
}

.navigation {
  margin: 30px 0;
}

.nav-btn {
  background: rgba(100, 108, 255, 0.3); /* 半透明蓝色背景 */
  color: #ffffff; /* 白色文字 */
  border: 1px solid rgba(100, 108, 255, 0.5); /* 蓝色边框 */
  padding: 12px 24px;
  border-radius: 30px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1rem;
  backdrop-filter: blur(5px);
  box-shadow: 0 0 15px rgba(100, 108, 255, 0.3);
}

.nav-btn:hover {
  background: rgba(100, 108, 255, 0.5); /* 更不透明的背景 */
  transform: translateY(-2px);
  box-shadow: 0 5px 20px rgba(100, 108, 255, 0.5);
}

.music-status {
  margin-top: 20px;
  font-size: 0.9rem;
  opacity: 0.8;
  color: #aaaaaa; /* 浅灰色状态文字 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .title {
    font-size: 2rem;
  }
  
  .subtitle {
    font-size: 1rem;
  }
  
  .welcome-content {
    padding: 30px 20px;
  }
}
</style>